package vip.ifmm.lehouse.api.gateway.controller.commodity;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.*;
import vip.ifmm.lehouse.commodity.service.api.CommodityService;
import vip.ifmm.lehouse.common.bo.CommodityBo;
import vip.ifmm.lehouse.common.dto.ServerResponse;
import vip.ifmm.lehouse.common.enums.CommonStatus;
import vip.ifmm.lehouse.common.enums.status.CommodityStatus;
import vip.ifmm.lehouse.common.vo.CommodityVo;

/**
 * 商品服务控制器
 *
 * @author Fish
 * <p>Email: fishinlove@163.com</p>
 * <p>created by 2019/06/21 22:25:51</p>
 */
@RestController
@RequestMapping(path = "/commodity")
public class CommodityController {

    @Reference
    private CommodityService commodityService = null;

    @PostMapping(path = "/saveCommodity")
    public ServerResponse saveCommodity(@RequestBody String commodityBoJson) {
        CommodityBo commodityBo = JSON.parseObject(commodityBoJson, CommodityBo.class);

        try {
            return commodityService.saveCommodity(commodityBo);
        } catch (Exception e) {
            // 由于在 Service 中会抛出异常，以方便事务回滚，所以这里就需要进行捕获
            return ServerResponse.response(CommodityStatus.COMMODITY_SAVED_FAILED);
        }
    }

    @GetMapping(path = "/listCommodities")
    public ServerResponse listCommodities(@RequestParam(defaultValue = "1") Integer pageNum,
                                          @RequestParam(defaultValue = "16") Integer pageSize,
                                          @RequestParam(required = false) Integer typeId) {
        if (typeId == null) {
            // 没有使用商品分类 id 查询
            return commodityService.listCommodities(pageNum, pageSize);
        }

        // 使用商品分类 id
        return commodityService.listCommoditiesByTypeId(pageNum, pageSize, typeId);
    }

    @GetMapping(path = "/getCommodity")
    public ServerResponse getCommodity(Integer commodityId) {
        return commodityService.getCommodity(commodityId);
    }

    @PutMapping(path = "/updateCommodity")
    public ServerResponse updateCommodity(@RequestBody String commodityVoJson) {
        CommodityVo commodityVo = JSON.parseObject(commodityVoJson, CommodityVo.class);

        try {
            return commodityService.updateCommodity(commodityVo);
        } catch (Exception e) {
            // 由于在 Service 中会抛出异常，以方便事务回滚，所以这里就需要进行捕获
            return ServerResponse.response(CommodityStatus.COMMODITY_UPDATED_FAILED);
        }
    }
}
